﻿using System;
using System.Windows.Forms;

namespace GUI
{
    public partial class CreateNewForm : Form
    {
        public event MountEventHandler MountEvent;

        private enum Measure { KB = 0, MB, GB }
        public CreateNewForm()
        {
            InitializeComponent();
            driveLetterCBox.DataSource = DriveManagement.DriveManager.FreeLetters;
            measureCBox.SelectedIndex = 1;
        }
        private Int64 GetMeasuredSize(int measureIndex, long size)
        {//calculatin size in bytes from selected measure
            switch ((Measure)measureIndex)
            {
                case Measure.KB: return 1024 * size;
                case Measure.MB: return 1024 * 1024 * size;
                case Measure.GB: return 1024 * 1024 * 1024 * size;
                default: throw new ArgumentOutOfRangeException("measureCBox.SelectedIndex", "You are a magician or a hacker:)");
            }
        }

        private void okBtn_Click(object sender, EventArgs e)
        {
            try
            {
                long fileSize;// one more comparison or few converts between ulong and long further
                if (long.TryParse(sizeTBox.Text, out fileSize) != false && fileSize > 0)
                {
                    DriveManagement.DriveManager.CreateFile(saveFileDialog.FileName, GetMeasuredSize(measureCBox.SelectedIndex, fileSize));
                    if (MountEvent != null)
                        MountEvent(driveLetterCBox.Items[driveLetterCBox.SelectedIndex].ToString()[0], passwordTBox.Text, saveFileDialog.FileName);
                    sizeTBox.Clear();
                    passwordTBox.Clear();
                    driveLetterCBox.SelectedIndex++;
                    Close();
                }
                else
                {
                    MessageBox.Show(GUI.Resources.Strings.NonInt);
                    sizeTBox.Clear();
                    sizeTBox.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void CreateNewForm_Load(object sender, EventArgs e)
        {
            try
            {
                if (saveFileDialog.ShowDialog() != DialogResult.OK)
                    Close();
            }
            catch (Exception)//
            {
                Dispose();
            }
        }

        private void cancelBtn_Click(object sender, EventArgs e)
        {
            try
            {
                Close();
                sizeTBox.Clear();
            }
            catch (Exception)//
            {
                Dispose();
            }
        }
    }
}
